# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
import logging
import pprint
import sys

from tornado import gen
from tornado.ioloop import IOLoop

from coin.base.config import Config
from coin.exchange.base.order_gateway import OrderSide, OrderType
from coin.exchange.okex.order_gateway import OkexOrderGateway
from coin.exchange.okex.kr_rest.product import OkexProduct
from coin.exchange.okex.kr_rest.public_client import OkexPublicClient
from coin.exchange.okex.kr_rest.currency import OkexCurrency


def round_up(num):
  return round(num * 1e8) / 1e8


class TestDriver(object):
  def __init__(self, ioloop):
    self._ioloop = ioloop
    self._currencies = [OkexCurrency.FromStrCurrency(currency) for currency in ('XRP', 'BTC')]
    self._product = OkexProduct.FromStr('XRP-BTC')
    self._og = OkexOrderGateway(self._currencies, [self._product],
                                Config.from_config_filename('okex_pilot01'))
    self._og.start(self._ioloop)
    self._ioloop.add_timeout(datetime.timedelta(seconds=5), self.print_balance)
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.loop)
    self._public_client = OkexPublicClient()

  def print_balance(self):
    if self._og.is_ready():
      print('------------------------')
      print(datetime.datetime.now())
      for currency in self._currencies:
        print(currency.symbol, self._og.get_balance(currency.symbol))
      pprint.pprint(self._og.get_working_order())
    self._ioloop.add_timeout(datetime.timedelta(seconds=30), self.print_balance)

  @gen.coroutine
  def loop(self):
    self._og.cancel_all()
    update = self._public_client.query_ticker(self._product)
    last_price = update.msg.last
    self._og.submit(self._product, round_up(last_price), 1, OrderSide.BUY, OrderType.LIMIT)
    self._og.submit(self._product, round_up(last_price), 1, OrderSide.SELL, OrderType.LIMIT)

    yield gen.sleep(20)
    self._og.cancel_all()
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.loop)


def main(argv):
  ioloop = IOLoop.current()
  driver = TestDriver(ioloop)
  try:
    ioloop.start()
  except KeyboardInterrupt:
    pass


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s.%(msecs)03d %(name)s %(filename)s:%(lineno)s] %(message)s',
      datefmt='%Y%m%d %H:%M:%S')
  sys.exit(main(sys.argv))
